package com.ncpowernode.javaweb.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class SqlSessionUtil {

    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> local = new ThreadLocal<>();

    private SqlSessionUtil(){}

    static{
        synchronized (SqlSessionUtil.class){
            try {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static SqlSession openSession(){
        SqlSession session = local.get();
        if(session==null){
            session = sqlSessionFactory.openSession();
            local.set(session);
        }
        return session;
    }

    public static void close(){
        SqlSession session = local.get();
        if(session!=null){
            local.remove();
            session.close();
        }
    }

}
